package com.tanhua.manage.listener;
import java.util.Date;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.tanhua.manage.domain.Log;
import com.tanhua.manage.service.LogService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 日志消息监听器：监听tanhua-log-152主题的日志消息，实现记录日志到日志表
 * @RocketMQMessageListener
 * 1. 消息监听器注解
 * 2. topic  监听的主题，与消息发送者指定的主题要一致
 * 3. consumerGroup 消费者组，多个消费者组名称一致，消费消息时候相同组名称的消费者只有一个会消费消息
 *                  避免消息重复消费。
 */
@Component
@RocketMQMessageListener(topic = "tanhua-log-152",consumerGroup = "tanhua-log-consumer152")
public class LogMessageListener implements RocketMQListener<String>{
    @Autowired
    private LogService logService;

    @Override
    public void onMessage(String message) {
        // 消息内容: message = {"date":"2021-06-19","type":"0101","userId":"1"}
        // 转换
        Map<String,String> map = JSON.parseObject(message, Map.class);
        // 获取消息内容
        Long userId = Long.parseLong(map.get("userId")+"");
        String type = map.get("type");
        String date = map.get("date");
        // 创建并封装日志对象
        Log log = new Log();
        log.setUserId(userId);
        log.setLogTime(date);
        log.setType(type);
        log.setCreated(new Date());
        log.setUpdated(new Date());

        // 记录日志
        logService.save(log);
    }
}
